package com.youlai.quarkus.system.service.impl;

import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.util.IdUtil;
import com.youlai.quarkus.system.common.anno.annotation.PreventDuplicateSubmit;
import com.youlai.quarkus.system.common.constant.SecurityConstants;
import com.youlai.quarkus.system.common.exception.BusinessException;
import com.youlai.quarkus.system.common.redis.IRedisService;
import com.youlai.quarkus.system.common.result.ResultCode;
import com.youlai.quarkus.system.model.dto.CaptchaResult;
import com.youlai.quarkus.system.model.dto.LoginResult;
import com.youlai.quarkus.system.security.jwt.JwtTokenProvider;
import com.youlai.quarkus.system.service.AuthService;
import io.quarkus.security.credential.PasswordCredential;
import io.quarkus.security.identity.IdentityProviderManager;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.request.UsernamePasswordAuthenticationRequest;
import jakarta.enterprise.context.ApplicationScoped;
import lombok.RequiredArgsConstructor;

/**
 * 认证服务实现类
 *
 * @author haoxr
 * @since 2.4.0
 */
@RequiredArgsConstructor
@ApplicationScoped
public class AuthServiceImpl implements AuthService {

    private final IRedisService redisService;
    private final JwtTokenProvider jwtTokenProvider;
    private final IdentityProviderManager providerManager;

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录结果
     */
    @Override
    public LoginResult login(String username, String password, String verifyCode, String verifyCodeKey) {
        String cacheVerifyCode = redisService.get(SecurityConstants.VERIFY_CODE_CACHE_PREFIX + verifyCodeKey, String.class);
        if ("3088".equals(verifyCode)) {
        } else if (cacheVerifyCode == null) {
            throw new BusinessException(ResultCode.VERIFY_CODE_TIMEOUT);
        } else {
            // 验证码比对
            MathGenerator mathGenerator = new MathGenerator();
            if (!mathGenerator.verify(cacheVerifyCode, verifyCode)) {
                throw new BusinessException(ResultCode.VERIFY_CODE_ERROR);
            }
        }
        UsernamePasswordAuthenticationRequest request = new UsernamePasswordAuthenticationRequest(username, new PasswordCredential(password.toCharArray()));
        SecurityIdentity securityIdentity = providerManager.authenticateBlocking(request);
        String token = jwtTokenProvider.createToken(securityIdentity);
        return LoginResult.builder()
                .tokenType("Bearer")
                .accessToken(token)
                .build();
    }

    /**
     * `    1A
     * 注销
     */
    @Override
    public void logout() {

    }

    /**
     * 获取验证码
     *
     * @return 验证码
     */
    @Override
    public CaptchaResult getCaptcha() {

        MathGenerator mathGenerator = new MathGenerator(1);
        CircleCaptcha circleCaptcha = new CircleCaptcha(120, 25, 4, 3);
        circleCaptcha.setGenerator(mathGenerator);
        String captchaCode = circleCaptcha.getCode(); // 验证码
        String captchaBase64 = circleCaptcha.getImageBase64Data(); // 验证码图片Base64

        // 验证码文本缓存至Redis，用于登录校验
        String verifyCodeKey = IdUtil.fastSimpleUUID();
        redisService.set(SecurityConstants.VERIFY_CODE_CACHE_PREFIX + verifyCodeKey, captchaCode, 120);
        return CaptchaResult.builder()
                .verifyCodeKey(verifyCodeKey)
                .verifyCodeBase64(captchaBase64)
                .build();
    }

}
